package com.example.demo.service.impl;

import cn.hutool.core.io.FileUtil;
import com.example.demo.entity.BdEntry;
import com.example.demo.service.EntryService;
import com.google.common.collect.Maps;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Map;

@Service
public class EntryServiceImpl implements EntryService {
    @Value("${file.path}")
    private String filePath;

    public void exportToPdf(BdEntry bdEntry, HttpServletResponse response) throws DocumentException, IOException {
        Map<String, Object> paramsa =Maps.newHashMap();
        paramsa.put("constructionCertificate", bdEntry.getConstructionCertificate());
        paramsa.put("truckCertificate", bdEntry.getTruckCertificate());
        String[] uploadPoints = bdEntry.getUnloadingPoint().split(",");
        for (int i=0;i< uploadPoints.length;i++){
            paramsa.put(uploadPoints[i],uploadPoints[i]);
        }
        String[] freightMovementLines = bdEntry.getFreightMovementLine().split(",");
        for (int i=0;i< freightMovementLines.length;i++){
            paramsa.put(freightMovementLines[i],freightMovementLines[i]);
        }
        String[] elevators = bdEntry.getElevatorsUsed().split(",");
        for (int i=0;i< elevators.length;i++){
            paramsa.put(elevators[i],elevators[i]);
        }
        paramsa.put("elevatorNotes", bdEntry.getElevatorNotes());
        paramsa.put("groundProtection1", bdEntry.getGroundProtection1());
        paramsa.put("groundProtection2", bdEntry.getGroundProtection2());
        paramsa.put("groundProtection3", bdEntry.getGroundProtection3());
        paramsa.put("groundProtection4", bdEntry.getGroundProtection4());
        paramsa.put("groundProtection5", bdEntry.getGroundProtection5());
        paramsa.put("groundProtection6", bdEntry.getGroundProtection6());
        paramsa.put("groundProtectionNotes", bdEntry.getGroundProtectionNotes());
        paramsa.put("decorationProtection1", bdEntry.getDecorationProtection1());
        paramsa.put("decorationProtection2", bdEntry.getDecorationProtection2());
        paramsa.put("decorationProtection3", bdEntry.getDecorationProtection3());
        paramsa.put("decorationProtection4", bdEntry.getDecorationProtection4());
        paramsa.put("decorationProtection5", bdEntry.getDecorationProtection5());
        paramsa.put("decorationProtection6", bdEntry.getDecorationProtection6());
        paramsa.put("decorationProtection7", bdEntry.getDecorationProtection7());
        paramsa.put("decorationProtection8", bdEntry.getDecorationProtection8());
        paramsa.put("decorationProtectionNotes", bdEntry.getDecorationProtectionNotes());
        paramsa.put("pollutionControl1", bdEntry.getPollutionControl1());
        paramsa.put("pollutionControl2", bdEntry.getPollutionControl2());
        paramsa.put("pollutionControl3", bdEntry.getPollutionControl3());
        paramsa.put("pollutionControl4", bdEntry.getPollutionControl4());
        paramsa.put("pollutionControl5", bdEntry.getPollutionControl5());
        paramsa.put("pollutionControl6", bdEntry.getPollutionControl6());
        paramsa.put("pollutionControl7", bdEntry.getPollutionControl7());
        paramsa.put("pollutionControl8", bdEntry.getPollutionControl8());
        paramsa.put("pollutionControlNotes", bdEntry.getPollutionControlNotes());
        paramsa.put("wallInsert", bdEntry.getWallInsert());
        paramsa.put("wallInsertNum", bdEntry.getWallInsertNum());
        paramsa.put("wallInsertPlace", bdEntry.getWallInsertPlace());
        paramsa.put("groundInsertion", bdEntry.getGroundInsertion());
        paramsa.put("groundInsertionNum", bdEntry.getGroundInsertionNum());
        paramsa.put("groundInsertionPlace", bdEntry.getGroundInsertionPlace());
        paramsa.put("aviationPlug", bdEntry.getAviationPlug());
        paramsa.put("aviationPlugNum", bdEntry.getAviationPlugNum());
        paramsa.put("aviationPlugPlace", bdEntry.getAviationPlugPlace());
        paramsa.put("electricBox", bdEntry.getElectricBox());
        paramsa.put("electricBoxNum", bdEntry.getElectricBoxNum());
        paramsa.put("electricBoxPlace", bdEntry.getElectricBoxPlace());
        paramsa.put("strongCurrentRoom", bdEntry.getStrongCurrentRoom());
        paramsa.put("strongCurrentRoomNum", bdEntry.getStrongCurrentRoomNum());
        paramsa.put("strongCurrentRoomPlace", bdEntry.getStrongCurrentRoomPlace());
        paramsa.put("diningIn", bdEntry.getDiningIn());
        paramsa.put("diningInNum", bdEntry.getDiningInNum());
        paramsa.put("diningOut", bdEntry.getDiningOut());
        paramsa.put("diningIntTime", bdEntry.getDiningInTime());


        // 利用模板生成pdf
        String templatePath = filePath+"entryTemplate.pdf";

        // 生成的新文件路径
        String caseId = "进场单"+ bdEntry.getId().toString()+".pdf";
        String newPDFPath = "D:\\system\\system-back\\files\\pdf\\" + caseId;

        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            for (String key : paramsa.keySet()) {
                if (paramsa.get(key)==null){
                    paramsa.put(key,"");
                }
                form.setField(key,paramsa.get(key).toString(),true);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            copy.open();
            doc.open();
//            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
//            copy.addPage(importPage);
            PdfImportedPage importPage=null;
            for (int i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }
            copy.close();
            doc.close();
            out.close();
        } catch (IOException | DocumentException e) {
            throw new RuntimeException(e);
        }

        try {
            OutputStream os;  // 新建一个输出流对象
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(caseId, "UTF-8"));
            response.setContentType("application/octet-stream");
            byte[] bytes = FileUtil.readBytes(newPDFPath);  // 通过文件的路径读取文件字节流
            os = response.getOutputStream();   // 通过输出流返回文件
            os.write(bytes);
            os.flush();
            os.close();
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }


}
